package com.bzkj.inventory.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bzkj.common.constant.NccStatusConstant;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.domain.NccApiResponse;
import com.bzkj.common.utils.http.NccHttpUtils;
import com.bzkj.inventory.domain.dto.UpdateValidateDTO;
import com.bzkj.inventory.service.ValidateManageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @projectName: prt-wms
 * @package: com.bzkj.inventory.service.impl
 * @className: ValidateManageServiceImpl
 * @description: 批次管理服务层
 * @author: C1309
 * @createDate: 2024年12月13日
 * @version: v1.0
 */
@Service
public class ValidateManageServiceImpl implements ValidateManageService {

    @Resource
    private NccHttpUtils nccHttpUtils;


    /**
     * 更新批次档案有效期
     *
     * @param validateDTO 更新批次档案有效期
     * @return 操作结果
     */
    @Override
    public AjaxResult updateValidateManage(UpdateValidateDTO validateDTO) {
        try {
            NccApiResponse nccApiResponse = nccHttpUtils.post("/nccloud/api/uapbd/scmbatchcode/updatedvalidate", JSONObject.toJSONString(validateDTO));
            validateNccResponse(nccApiResponse);
            // 解析返回结果

            return handleSuccessResponse(nccApiResponse);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("小提示：更新批次档案失效日期时遇到了一点小问题，可能是网络不太顺畅或者接口出了点状况。别急，检查下网络连接，再试一次吧！如果有持续的问题，记得联系技术支持哦～", e);
        }
    }

    /**
     * 处理成功响应的方法
     */
    private AjaxResult handleSuccessResponse(NccApiResponse nccResponseMap) {

//        ArrayList<HashMap<String, Object>> parsedDataList = parsingMaterialOutboundOrders(nccResponseMap);
//        HashMap<String, Object> parseData = parsedDataList.get(0);
//        HashMap<String, Object> header = (HashMap<String, Object>) parseData.get("header");
//
//        // 生成单据号
//        String wmsMatOutNo = documentNoUtils.generateMatOrderNumber();
//        header.put("vdef49", wmsMatOutNo);
//        header.put("vdef50", wmsMatOutNo);
//
//        // 写入数据库
//        int resultNum = materialOutboundMapper.addMaterialOrderHeader(header);
//
//        if (resultNum > 0) {
//            List<HashMap<String, Object>> detailsList = (List<HashMap<String, Object>>) parseData.get("details");
//            for (HashMap<String, Object> detailMap : detailsList) {
//                materialOutboundMapper.addMaterialOrderDetails(detailMap);
//            }
//        }

        return AjaxResult.success("太棒啦！更新批次档案失效日期更新成功，辛苦啦~");
    }


    /**
     * 验证 NCC 响应状态
     *
     * @param nccApiResponse NCC 返回结果
     */
    public  void validateNccResponse(NccApiResponse nccApiResponse) {
        String responseCode = nccApiResponse.getCode();

        if (NccStatusConstant.SUCCESS_CODE.equals(responseCode)) {
            return; // 成功，无需处理
        }

        if (NccStatusConstant.BUSINESS_ERROR_CODE.equals(responseCode)) {
            String message = nccApiResponse.getMessage();
            String errorStack = nccApiResponse.getErrorStack();

            // 提取首条业务异常信息
            String extractedError = extractFirstBusinessException(errorStack);
            throw new RuntimeException(message + ": " + extractedError);
        }

        // 处理其他未知错误
        throw new RuntimeException("未知错误：" + nccApiResponse);
    }

    /**
     * 提取errorStack中的首条业务异常信息
     *
     * @param errorStack 完整的堆栈信息
     * @return 首条业务异常信息
     */
    private static String extractFirstBusinessException(String errorStack) {
        if (errorStack == null || errorStack.isEmpty()) {
            return "No error stack available";
        }

        // 查找包含 "BusinessException" 的行
        String[] lines = errorStack.split("\\r?\\n");
        for (String line : lines) {
            if (line.contains("BusinessException")) {
                // 提取异常信息部分
                int index = line.indexOf(":");
                return index != -1 ? line.substring(index + 1).trim() : line.trim();
            }
        }

        return "No BusinessException found";
    }
}
